﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;

namespace Event_SG_EWDT
{
    /// <summary>
    /// Summary description for HTTPHandler
    /// Handles the request of browser to display images from bytes
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class HTTPHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string imageID = context.Request.QueryString["imageid"];
            context.Response.ContentType = "image/jpeg";
            Stream strm = RetrieveImage(imageID);
            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);

            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }       
 
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public Stream RetrieveImage(string imageid)//ok
        {
            SqlConnection conn = null;
            object img = new object();

                conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["EventSGDBString"].ConnectionString;
                conn.Open();
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                comm.CommandText = "select image from Image where image_id=@image_id";
                comm.Parameters.AddWithValue("@image_id", Convert.ToInt32(imageid));
                img = comm.ExecuteScalar();
               
            try
            {
                return new MemoryStream((byte[])img);
            }
            catch
            {
                return null;
            }
                finally
            {
                conn.Close();
            }

            
        }
    }
}